import fs from "fs";
import { findfiles } from "./findfiles";
import { startall } from "./startall";
import path from "path";
import { mdreg, markdownlistener } from "./createprerenderplugin";
import { getmenulist } from "./getmenulist";
import { getlocalpathfrombaseurl } from "./getlocalpathfrombaseurl";
import { Deduplication } from "../src/Deduplication";

export async function onlistenstart({
    root,
    baseurl,
}: {
    root: string;
    baseurl: string;
}): Promise<void> {
    async function watchfile() {
        const menulist = await getmenulist();
        const localmdfiles = await Promise.all(
            menulist
                .filter((a) => a.startsWith(baseurl))
                .map((url) => getlocalpathfrombaseurl(url, baseurl))
        );
        fs.watch(root, (eventType, filename) => {
            if (mdreg.test(filename)) {
                markdownlistener();
            }
        });
        fs.watch(path.join(root, "docs"), (eventType, filename) => {
            if (mdreg.test(filename)) {
                markdownlistener();
            }
        });
        const mdfiles = await findfiles(mdreg, path.join(root, "docs"));
        Deduplication([...localmdfiles, ...mdfiles]).forEach((filename) => {
            fs.watchFile(filename, () => {
                markdownlistener();
            });
        });
    }
    if (
        process.env.NODE_ENV == "development" &&
        process.env.WEBPACK_SERVE === "true"
    ) {
        await watchfile();
    }
    return startall();
}
